﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<link href="js-console.css" rel="stylesheet" />
	<!-- 6. Write a function that groups an array of persons by 
			age, first or last name. The function must return an 
			associative array, with keys - the groups, and values -arrays with persons in this groups
			* Use function overloading (i.e. just one function)
			var persons = {…};
			var groupedByFname = group(persons,"firstname");
			var groupedByAge= group(persons,"age"); -->
	<style>
		strong, em {
			text-decoration: underline;
		}
		em{
			padding-left: 20px;
		}
	</style>
</head>
<body>
	<div id="js-console"></div>
	<script src="js-console.js"></script>
	<script>
		// Result function
		function group(persons, property) {
			var res = {};

			// For all persons
			for (var i = 0; i < persons.length; i++) {
				// Get the values of selected property
				var value = persons[i][property];

				// Check if there is a property with that name in the destination object
				if (res[value] == undefined) {
					res[value] = new Array(persons[i]);	// new Array if missing
				}
				else {
					res[value].push(persons[i]);		// Add person to the Array
				}
			}

			return res;
		}

		// Presentation of a group to the jsConsole
		function printGroup(group) {
			for (var i in group) {
				// Print group value - its index
				jsConsole.write("<em>" + i + "</em>: ");
				// Print the array of persons - its value
				jsConsole.writeLine(group[i].join(', '));
			}
		}

		// Person object (with toString override)
		function Person(firstname, lastname, age) {
			this.firstname = firstname;
			this.lastname = lastname;
			this.age = age;
			this.toString = function () { return "{" + this.firstname + " " + this.lastname + " age: " + this.age + "}" };
		}

		// Construct Array with persons
		var persons = [
						new Person("Gosho", "Petrov", 32),
						new Person("Pesho", "Dimitrov", 18),
						new Person("Pesho", "Petrov", 22),
						new Person("Ivan", "Ivanov", 22),
						new Person("Bay", "Ivan", 81),
						new Person("Baby", "Ivanov", 1),
						new Person("Baby", "Gosho", 1),
						new Person("Baby", "Petrov", 2)
		];


		// Sort the array
		persons.sort();

		// Print the array of persons
		jsConsole.writeLine("<strong>All persons</strong>");
		jsConsole.writeLine("[ " + persons.join(', ') + " ]");

		// Make different groups
		var groupedByFname = group(persons, "firstname");
		jsConsole.writeLine("<strong>Persons grouped by first name</strong>");
		printGroup(groupedByFname);

		var groupedByLname = group(persons, "lastname");
		jsConsole.writeLine("<strong>Persons grouped by last name</strong>");
		printGroup(groupedByLname);

		var groupedByAge = group(persons, "age");
		jsConsole.writeLine("<strong>Persons grouped by age</strong>");
		printGroup(groupedByAge);
	</script>
</body>
</html>
